//
//  ClubTableViewController.swift
//  yuejian
//
//  Created by gyy on 2017/10/26.
//  Copyright © 2017年 gyy. All rights reserved.
//

import UIKit

class ClubTableViewController: UITableViewController,clubListDelegate,DistanceListDelegate {
    @IBOutlet var tableview: UITableView!
    var clubList:NSMutableArray!
    var DistanceList:NSMutableArray!
    var flag:Bool = true
    var ClubBtn:UIButton!
    var OtherBtn:UIButton!
    var pageControl:UIPageControl?
    var myscrollView:UIScrollView?
    var myTimer:Timer?
    var mycurrentPage:NSInteger?
    var courses = [
        ["name":"健身俱乐部","pic":"ad0.jpg"],
        ["name":"瑜伽俱乐部","pic":"ad1.jpg"],
        ["name":"篮球俱乐部","pic":"ad2.jpg"],
        ["name":"慢跑俱乐部","pic":"ad3.jpg"]
    ]
    let screenSize: CGRect = UIScreen.main.bounds
    let kScreenWidth = UIScreen.main.bounds.size.width
    
    let kScreenHeight = UIScreen.main.bounds.size.height
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        getClubList()
        getDistanceList()
        self.tableview.delegate = self
        self.tableview.dataSource = self
        //getClubList()
        
        //添加scrollview
        self.addScrollView()
        //添加图片
        self.addImages()
        //添加pagecontrol
        self.addPageControl()
        
        mycurrentPage = 1
        
        //添加定时器
        self.setupTimer()
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
    func addScrollView(){
        
        self.myscrollView = UIScrollView()
        self.myscrollView?.frame = CGRect(x:0,y:0,width: kScreenWidth,height:kScreenHeight/4)
        self.myscrollView?.contentSize = CGSize(width: kScreenWidth*3,height:kScreenHeight/4)
        self.myscrollView?.showsHorizontalScrollIndicator = false
        self.myscrollView?.showsVerticalScrollIndicator = false
        self.myscrollView?.scrollsToTop = false
        self.myscrollView?.delegate = self
        self.myscrollView?.isPagingEnabled = true
        self.view.addSubview(self.myscrollView!)
        
    }
    
    func addImages(){
        let size = self.myscrollView?.bounds.size
        for (seq,course) in courses.enumerated() {
            let page = UIView(frame:CGRect(x:0,y:0,width:kScreenWidth,height:kScreenHeight/4))
            let imageView=UIImageView(image:UIImage(named:course["pic"]!))
            imageView.frame = page.frame
            page.addSubview(imageView)
            //page.backgroundColor = UIColor.lightGray
            let lab1 = UILabel(frame:CGRect(x:10,y:kScreenHeight/2-200,width:kScreenWidth/4,height:20))
            lab1.textAlignment = .center
            lab1.backgroundColor = UIColor.lightGray
            lab1.text = course["name"]
            page.addSubview(lab1)

            page.frame = CGRect(x:CGFloat(seq)*(size?.width)!,y:0,width:(size?.width)!,height:(size?.height)!)
            self.myscrollView?.addSubview(page)

        }
    }
    
    func addPageControl(){
        self.pageControl = UIPageControl(frame:CGRect(x:kScreenWidth/2,y:kScreenHeight/4-20,width:60,height:15))
        self.pageControl?.backgroundColor = UIColor.black
        self.pageControl?.numberOfPages = courses.count
        self.view.addSubview(self.pageControl!)
    }
    
    func setupTimer() {
        self.myTimer = Timer.init(timeInterval: 3.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        RunLoop.main.add(self.myTimer!, forMode: RunLoopMode.defaultRunLoopMode)
        
        //        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
        //            self.myTimer?.fire()
        //        }
        
    }
    
    func closeTimer(){
        self.myTimer?.invalidate()
        self.myTimer = nil
    }
    
    func timerAction(){
        self.pageControl?.currentPage += mycurrentPage!
        
        if self.pageControl?.currentPage == 0 || self.pageControl?.currentPage == 2 {
            mycurrentPage = -mycurrentPage!
        }
        self.myscrollView?.contentOffset = CGPoint(x:CGFloat(kScreenWidth)*CGFloat((pageControl?.currentPage)!),y:0)
    }

    func setView(){
        tableView.backgroundColor = UIColor.lightGray
        tableView.refreshControl = UIRefreshControl()
        tableView.refreshControl?.addTarget(self, action: #selector(refreshData), for: .valueChanged)
        tableView.register(ClubListCell.self, forCellReuseIdentifier: "ClubListCell")
        tableView.register(DistanceTableViewCell.self, forCellReuseIdentifier: "DistanceTableViewCell")
        let headView = UIView(frame: CGRect(x:0, y:0, width: view.bounds.width, height: 206))
        ClubBtn = UIButton(frame: CGRect(x: 0, y: kScreenHeight/4, width: view.bounds.width/2, height: 40.5))
        ClubBtn.backgroundColor = UIColor.gray
        ClubBtn.addTarget(self, action: #selector(showClubList), for: .touchUpInside)
        ClubBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        ClubBtn.setTitle("最具人气", for: .normal)
        ClubBtn.titleLabel?.textAlignment = .center
        headView.addSubview(ClubBtn)
        
        OtherBtn = UIButton(frame: CGRect(x: view.bounds.width/2, y: kScreenHeight/4, width: view.bounds.width/2, height: 40.5))
        OtherBtn.backgroundColor = UIColor.gray
        OtherBtn.addTarget(self, action: #selector(showDistanceList), for: .touchUpInside)
        OtherBtn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        OtherBtn.setTitle("离我最近", for: .normal)
        OtherBtn.titleLabel?.textAlignment = .center
        headView.addSubview(OtherBtn)
        
        tableView.tableHeaderView = headView
    }
    
    @objc func showClubList(){
        flag = true
        DistanceList = nil
        self.getClubList()
        tableView.reloadData()
        
    }
    @objc func showDistanceList(){
        flag = true
        clubList = nil
        self.getDistanceList()
        tableView.reloadData()
        
    }
    
    func getDistanceList(){
       let urlStr = "http://172.24.10.175/workout/api.php/nearclub"
      let paraDict = ["sessionid":SessionID]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let array = data as! NSArray
            //print(array)
           self.DistanceList = array.mutableCopy() as! NSMutableArray
            //print(self.DistanceList)
            self.tableView.reloadData()
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }

    }
    
    func getClubList(){
        let urlStr =  YJ_GetClubList
        let paraDict = ["sessionid":SessionID]
        AFHTTPRequestOperationManager().post(urlStr, parameters: paraDict, success: { (response:AFHTTPRequestOperation?, data:Any?) in
            let array = data as! NSArray
            //print(array)
            self.clubList = array.mutableCopy() as! NSMutableArray
            //print(self.clubList)
            self.tableView.reloadData()
        }) { (response:AFHTTPRequestOperation?, error:Error?) in
            print(response!.debugDescription)
        }
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if flag && clubList != nil{
            return clubList.count
        }else if !flag && DistanceList != nil{
            return DistanceList.count
        }
        
        return 0
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let basicCell:UITableViewCell? = nil
        if flag && clubList != nil{
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubListCell", for: indexPath) as! ClubListCell
            cell.selectionStyle = .none
            let dict = clubList[indexPath.row] as! NSDictionary
            //print(dict)
            cell.indexPath = indexPath
            cell.clubDelegate = self
            let pURL = "http://172.24.10.175/workout/Uploads/"
            let Thumb = dict["thumb"] as? String
            var imageUrl = URL(string: (pURL+Thumb!))
            cell.ClubPhoto!.setImageWith(imageUrl, placeholderImage: UIImage(named: "placeHolder"))
            cell.club_name.text =  dict["club_name"] as? String
            
            return cell
        }else if !flag && DistanceList != nil{
            let cell = tableView.dequeueReusableCell(withIdentifier: "DistanceTableViewCell", for: indexPath) as! DistanceTableViewCell
            let dict = DistanceList[indexPath.row] as! NSDictionary
            //print(dict)
            cell.selectionStyle = .none
            cell.indexPath = indexPath
            cell.DistanceDelegate = self
            let pURL = "http://172.24.10.175/workout/Uploads/"
            let Thumb = dict["thumb"] as? String
            var imageUrl = URL(string: (pURL+Thumb!))
            cell.ClubPhoto!.setImageWith(imageUrl, placeholderImage: UIImage(named: "placeHolder"))
            cell.club_name.text = dict["club_name"] as? String
    
            return cell
        }
        return basicCell!
    }
    
    @objc func refreshData(){
        if flag && clubList != nil{
            getClubList()
            tableView.reloadData()
            tableView.refreshControl?.endRefreshing()
        }
        else if !flag && DistanceList != nil{
            getDistanceList()
            tableView.reloadData()
            tableView.refreshControl?.endRefreshing()
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) ->CGFloat {
        if flag{
            return 170
        }else{
            return 170
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let controller = ClubDetailViewController()
        controller.infoDict = clubList![indexPath.row] as! NSDictionary
        
        _ = navigationController?.pushViewController(controller, animated: true)
        //self.rdv_tabBarController.setTabBarHidden(true, animated: true)
    }
    
}


